<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { ElTable, ElMessageBox, FormInstance, type FormRules, ElMessage } from "element-plus"
// 接口
import {
  getTeamDataApi,
  createTeamDataApi,
  delTeamDataApi,
  putTeamDataApi,
  getDepartment,
  rechargeRecord
} from "@/api/team"
import { type getTeamData } from "@/api/team/types/team"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh, Download } from "@element-plus/icons-vue"
const loading = ref(true)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "teamList"
})

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  name: "",
  source: ""
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTeam()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTeam()
    console.log("查询")
  }
  paginationData.currentPage = 1
}
// #endregion

// #region 改
const teamId = ref<undefined | string>(undefined)
const teamName = ref<undefined | string>(undefined)
const handleUpdate = (row: getTeamData) => {
  teamId.value = row.id
  teamName.value = row.name
  formData.name = row.name
  formData.department = row.source
  formData.type = row.type
  // console.log(row, "dangqian")

  dialogVisible.value = true
}
// #endregion

// #region 删
const handleDelete = (row: getTeamData) => {
  ElMessageBox.confirm(`您确定要删除:${row.name}团队吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delTeamDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTeam()
    })
  })
}
// #endregion

// #region 增
const tableDataT = ref()
const getTeam2 = () => {
  getDepartment({
    page: 1,
    size: 1000
  })
    .then((res: any) => {
      tableDataT.value = res.data.list
      console.log("--部门名", res.data.list)
    })
    .catch(() => {
      tableDataT.value = []
    })
}
getTeam2()
// #endregion

// #region
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  name: "",
  type: "",
  department: ""
})
const dialogVisible = ref<boolean>(false)
const rules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入团队名称" }],
  department: [{ required: true, trigger: "blur", message: "请输入部门名称" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (teamId.value === undefined) {
        createTeamDataApi({
          name: formData.name,
          type: formData.type,
          source: formData.department
        }).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          getTeam()
        })
      } else {
        putTeamDataApi({
          id: teamId.value,
          name: formData.name,
          type: formData.type,
          source: formData.department
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getTeam()
        })
      }
    } else {
      return false
    }
  })
}

const resetForm = () => {
  teamId.value = undefined
  clearValidate()
  formData.name = ""
}
// #endregion

// #region 查
const tableTotal = ref<number>()
const tableData = ref<getTeamData[]>([])
const getTeam = () => {
  getTeamDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    source: searchData.source || "",
    name: searchData.name || ""
  })
    .then((res: any) => {
      tableData.value = res.data.teamList
      tableTotal.value = res.data.total
      loading.value = false
      console.log("获取团队", res)
    })
    .catch(() => {
      tableData.value = []
    })
}
// #endregion

/** 订单下载 默认下载所有数据，查询后下载所有符合查询条件的数据*/
// const loading1 = ref<boolean>(false)
const downLoad = async () => {
  loading.value = true
  await rechargeRecord({
    source: searchData.source || "",
    name: searchData.name || ""
  }).then((res: any) => {
    const blob = new Blob([res.data], {
      type: "application/xlsx;charset=utf-8"
    })
    // console.log(res)
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "团队列表.xlsx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
    loading.value = false
  })
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTeam, { immediate: true })
const clearValidate = () => {
  formRef.value?.clearValidate()
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="source" label="部门名">
          <el-input v-model.trim="searchData.source" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item prop="name" label="团队名">
          <el-input v-model.trim="searchData.name" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 中间部分 -->
    <el-card shadow="never" v-loading="loading">
      <!-- 顶部添加职位 -->
      <div class="middle-top">
        <div>
          <el-button type="primary" @click="dialogVisible = true">添加团队</el-button>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="downLoad" />
          </el-tooltip>
        </div>
      </div>
      <!-- 中间渲染内容 -->
      <div class="table-center">
        <el-scrollbar height="500px">
          <el-table :data="tableData">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="id" label="ID" width="120" align="center" />
            <el-table-column prop="source" label="部门名" align="center" />
            <el-table-column prop="name" label="团队名" align="center" />
            <el-table-column prop="type" label="团队类型" align="center" />
            <el-table-column fixed="right" label="操作" width="150" align="center">
              <template #default="scope">
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="teamId === undefined ? '新增团队' : '修改团队'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="团队名">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="department" label="归属部门">
          <el-select v-model="formData.department" clearable placeholder="请选择部门" style="width: 240px">
            <el-option v-for="item in tableDataT" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item prop="type" label="团队类型">
          <el-select v-model="formData.type" clearable placeholder="请选择" style="width: 240px">
            <el-option key="1" label="天猫" value="天猫" />
            <el-option key="2" label="京东" value="京东" />
            <el-option key="3" label="拼多多" value="拼多多" />
            <el-option key="4" label="抖音" value="抖音" />
            <el-option key="5" label="新媒体" value="新媒体" />
            <el-option key="6" label="其它" value="其它" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
